package io.jt808.multiService;

import io.jt808.proto.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;

import java.util.Set;


@Component
public class PackageHolder {

    @Autowired
    private PackageItemTemplate packageItemTemplate;

    private String key = PackageHolder.class.getSimpleName() + "HashMap";

    public PackageHolder() {
    }

    public boolean isComplete(String primaryKey, String protoName) {
        String hkey = getHashKey(primaryKey, protoName);
        PackageItem packageItem = getHashOpts().get(key, hkey);
        return packageItem != null && packageItem.isComplete();
    }

    private String getHashKey(String primaryKey, String protoName) {
        return primaryKey + ":" + protoName;
    }

    private HashOperations<String, String, PackageItem> getHashOpts() {
        return packageItemTemplate.opsForHash();
    }

    public void push(Wrapper req) {
        String hkey = getHashKey(req.getTerminalSerialNo(), req.requestProtocol());
        PackageItem packageItem = getHashOpts().get(key, hkey);
        if (packageItem == null) {
            packageItem = new PackageItem();
            packageItem.setMessageSerialNo(req.getMessageSerialNo());
            packageItem.setTotalPackages(req.totalPackages());
            packageItem.setTerminalSerialNo(req.getTerminalSerialNo());
            packageItem.setRetransmissionTimes(0);
        }
        packageItem.addPackage(req.currentPackageNo(), req.getPackageData());
        packageItem.setUpdateTime(System.currentTimeMillis());
        getHashOpts().put(key, hkey, packageItem);
    }

    public PackageItem getAndRemovePackageItem(String primaryKey, String protoName) {
        String hkey = getHashKey(primaryKey, protoName);
        PackageItem packageItem = getHashOpts().get(key, hkey);
        getHashOpts().delete(key, hkey);
        return packageItem;
    }

    public PackageItem getPackageItem(String hashKey) {
        return getHashOpts().get(key, hashKey);
    }

    public Set<String> getHashKeySet() {
        return getHashOpts().keys(key);
    }

    public void remove(String hashKey) {
        getHashOpts().delete(key, hashKey);
    }

    public void update(String hkey, PackageItem packageItem) {
        getHashOpts().put(key, hkey, packageItem);
    }
}
